package lab_16.com.acme.bankapp.domain.bank;

import java.io.Serializable;
import java.util.*;

public class Client implements Serializable {

	/**
	 * 
	 */
	private static final long serialVersionUID = -4967337610845065669L;
	private Set<Account> accounts = new HashSet<Account>();
	private Gender gender;
	private String name;

	public Client(Gender gender, String name) {
		this.gender = gender;
		this.setName(name);

	}

	public Client(Gender gender, String name, Account firstAccount) {
		this(gender, name);
		addClientAccount(firstAccount);
	}

	@Override
	public int hashCode() {
		final int prime = 31;
		int result = 1;
		result = prime * result + ((gender == null) ? 0 : gender.hashCode());
		result = prime * result + ((name == null) ? 0 : name.hashCode());
		return result;
	}

	@Override
	public boolean equals(Object obj) {
		if (this == obj)
			return true;
		if (obj == null)
			return false;
		if (getClass() != obj.getClass())
			return false;
		Client other = (Client) obj;
		if (gender != other.gender)
			return false;
		if (name == null) {
			if (other.name != null)
				return false;
		} else if (!name.equals(other.name))
			return false;
		return true;
	}

	public String getClientSalutation() {
		return gender.getGreeting();
	}

	public void addClientAccount(Account account) {
		accounts.add(account);
	}

	public Set<Account> getAccounts() {
		return Collections.unmodifiableSet(accounts);
	}

	public void printAllClientData() {
		System.out.println(toString());
	}

	@Override
	public String toString() {
		StringBuilder builder = new StringBuilder();
		builder.append("---\n");
		builder.append(String.format("###Client: %1$s %2$s\n",
				getClientSalutation(), getName()));
		for (Account account : getAccounts()) {
			builder.append(account.toString());
		}
		builder.append("---");

		return builder.toString();
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	/**
	 * Get all client data as a string to write to file.
	 */
	public String getClientStreamData() {
		StringBuilder result = new StringBuilder();
		boolean first = true;
		for (Account account : accounts) {
			if (first) {
				first = false;
			} else {
				result.append("\n");
			}
			result.append(account.getAccountStreamData());
			result.append(String.format("name=%s;gender=%s;", name,
					gender.getSerialName()));
		}
		return result.toString();
	}
}
